import pytest
from selenium import webdriver
import time
from selenium.webdriver.common.by import By as by
from config import Config, getPath, pushOrderNumber
import json
import os
# 全局变量
from sendEmail import send_email
config = Config()


# assert断言方法
def isNot(w, c, p):
    try:
        w.find_element(c, p)
        return True
    except:
        return False


def setup_module():
    print('set up')


def fun(data):
    print('开始执行Testfun')
    web = webdriver.Chrome()
    # 隐等待
    web.implicitly_wait(5)
    # 窗口最大化
    web.maximize_window()
    # 访问登陆api
    web.get('https://www.jd.com')

    if os.path.exists('cookie.txt'):
        with open('cookie.txt', 'r', encoding='utf8') as f:
            listCookies = json.loads(f.read())
            print(f'cookie -->>  {listCookies}')
            for cookie in listCookies:
                web.add_cookie(cookie)
            # 读取完cookie刷新页面
            web.refresh()

    # 判断是否登陆
    if isNot(web, by.XPATH, '//*[@id="ttbar-login"]/div/a'):
        pass
    else:
        print('前往登陆')
        web.get(config.loginApi)
        print('获取地址信息')
        # print('data -- >> '+data)
        print(data['shippingAddress'])
        print('-----------')
        print(config.user)
        login = web.find_element(by.XPATH, '//*[@id="content"]/div[2]/div[1]/div/div[3]/a')
        login.click()
        # time.sleep(10)
        user_edit = web.find_element(by.XPATH, '//*[@id="loginname"]')
        pass_edit = web.find_element(by.XPATH, '//*[@id="nloginpwd"]')
        login_button = web.find_element(by.XPATH, '//*[@id="loginsubmit"]')
        user_edit.send_keys(config.user)
        pass_edit.send_keys(config.pasw)
        login_button.click()

        # user_view = web.find_element(by.XPATH, '//*[@id="ttbar-login"]/div/a')
        assert isNot(web, by.XPATH, '//*[@id="ttbar-login"]/div/a')
        print('成功登录')

        # 获取cookie
        dictCookies = web.get_cookies()
        jsonCookies = json.dumps(dictCookies)
        # print(jsonCookies)
        with open('cookie.txt', 'w') as f:
            f.write(jsonCookies)

    # 晴空购物车
    web.get('https://cart.jd.com/cart_index#none')

    web.get(data['batchUrl'])
    add_car = web.find_element(by.XPATH, '//*[@id="InitCartUrl"]')
    add_car.click()
    time.sleep(3)

    # 结算
    print('结算')
    toucart = web.find_element(by.XPATH, '//*[@id="GotoShoppingCart"]')
    toucart.click()
    # 去结算
    print('去结算')
    gojs = web.find_element(by.XPATH, "//*[text()='去结算']")
    gojs.click()

    try:
        print('点击新增地址')
        newaddPath = web.find_element(by.XPATH, '//*[@id="content"]/div[3]/div[1]/div[3]/a')
        newaddPath.click()
    except:
        print('您的账号没有任何地址')

    time.sleep(1)
    # 切换frame，如果没有切换成功 就点击新增地址按钮
    while (True):
        print('开始切换frame')
        try:
            # dialog = web.find_element(by.XPATH, '//*[@id="dialogIframe"]')
            web.switch_to.frame('dialogIframe')
            print('成功切换frame')
            break
        except:
            print('点击新增地址')
            newaddPath = web.find_element(by.XPATH, '//*[@id="content"]/div[3]/div[1]/div[3]/a')
            newaddPath.click()
            print('切换frame')
            time.sleep(2)

    print('选择地址')
    jscodde = """
        el = document.evaluate('//*[@id="jd_area"]', document).iterateNext();
        el.setAttribute("class",el.getAttribute("class")+" "+"ui-area-hover");
    """
    # 执行js代码,触发地址级联菜单
    web.execute_script(jscodde)
    print('循环地址')
    mpath = getPath(data['shippingAddress'])
    print(f"mpath -->> {mpath}")
    if mpath == None:
        print("地址为空")
        return False

    time.sleep(3)

    for i in range(4):
        uls = web.find_elements(by.CLASS_NAME, 'ui-area-content-list')
        li = uls[len(uls) - 1].find_elements(by.TAG_NAME, 'a')
        print(li)
        for l in li:
            print(l.text)
            if l.text in mpath['result']['analysis_address']:
                print(f'确定是{l.text}')
                if l.text == "":
                    print(f'l.text报空了')
                    break
                try:
                    dd = web.find_element(by.XPATH, f"//*[text()='{l.text}']")
                    dd.click()
                    # 如果想选择地址的时候快一点 可以修改下面的参数  5就是五秒
                    time.sleep(5)
                    break
                except:
                    print(f'没有找到{l.text}')

    print('收货人')
    p1 = web.find_element(by.XPATH, '//*[@id="consignee_name"]')
    p1.send_keys(data['consignee'])
    time.sleep(1)
    print('地址')

    p2 = web.find_element(by.XPATH, '//*[@id="consignee_address"]')
    p2.send_keys(mpath['result']['analysis_address'])
    time.sleep(1)

    print('电话')
    p3 = web.find_element(by.XPATH, '//*[@id="consignee_mobile"]')
    p3.send_keys(data['mobile'])
    time.sleep(1)

    print('保存地址')
    saveConfig = web.find_element(by.XPATH, '//*[@id="saveConsigneeTitleDiv"]')
    saveConfig.click()
    time.sleep(1)

    # 已弃用
    # web.switch_to_frame('mainframe')
    web.switch_to.default_content()
    time.sleep(1)

    print('提交订单')
    place_order = web.find_element(by.XPATH, '//*[@id="order-submit"]')
    place_order.click()
    time.sleep(2)
    print('请支付')

    # 获取发单号

    # 获取订单号
    orderNumber = web.find_element(by.XPATH, '//span[contains(text(), "订单号")]')
    # 如果订单号不为空就发送订单号
    if orderNumber != None:
        orderNumber = orderNumber.text.split("：")[1]
        print(orderNumber)
        # 发送订单号
        pushOrderNumber(orderNumber)

    # 提交当单号

    # if sendEmail('这里是发送内容，可以自己改'):
    #     print('发送成功')
    # else:
    #     print('发送失败')
    time.sleep(2)
    web.quit()


class TestJd():
    @pytest.mark.parametrize('data', config.testData['data'])
    def test_one(self, data):
        fun(data)


if __name__ == '__main__':
    pytest.main(['-s', './main.py', '--html=./report.html'])
    send_email('这里是发送内容，可以自己改')
